package com.elite;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.xml.rpc.holders.StringHolder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.tempuri.WebServiceTest;
import org.tempuri.WmgwLocator;

import com.dbic.sendMessage.client.MtNewMessage;
import com.dbic.sendMessage.client.SmsNewOperatorService;
import com.dbic.sendMessage.client.SmsNewOperatorServiceLocator;
import com.dbic.sendMessage.client.SmsNewOperator_PortType;



public class DBSMS implements Runnable{
	private static final Log log=LogFactory.getLog(DBSMS.class);
	public static com.elite.FtpBean ftpbean;
	public static String times;
	private boolean flag = true; 
	private static int Hz =1; 
	private static String sql =" select * from Documentout where DOCTYPE=3 and ((Status=0) or (Status!=1 and TrialCount<TrialCountLimit)) and expectedstartdate<=sysdate "; 
	private static String update_sql="";
	public static String username;
	public static String username1; 
	public static String password;
	public static String password1;
	public static String XHH;
	public static String XHH1;
	private static String LastTryDateTime="";
	private static String FinishDateTime="";
	public static String IP;
	private static int xh_int=0;
	private static SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
	
	
    private static String get_xh(int a){
    	if(a>=0&&a<10){
    		return "000"+a;
    	}else if(a>=10&&a<=99){
    		return "00"+a;
    	}else if(a>=100&&a<999){
    		return "0"+a;
    	}else{
    		return ""+a;
    	}
    }
	public static String getIP() {
		return IP;
	}
	public static void setIP(String ip) {
		IP = ip;
	}
	public static com.elite.FtpBean getFtpbean() {
		return ftpbean;
	}
	public static void setFtpbean(com.elite.FtpBean ftpbean) {
		DBSMS.ftpbean = ftpbean;
	}
	public static String getTimes() {
		return times;
	}
	public static void setTimes(String times) {
		DBSMS.times = times;
	}
	public static String getUsername() {
		return username;
	}
	public static void setUsername(String username) {
		DBSMS.username = username;
	}
	public static String getUsername1() {
		return username1;
	}
	public static void setUsername1(String username1) {
		DBSMS.username1 = username1;
	}
	public static String getPassword() {
		return password;
	}
	public static void setPassword(String password) {
		DBSMS.password = password;
	}
	public static String getPassword1() {
		return password1;
	}
	public static void setPassword1(String password1) {
		DBSMS.password1 = password1;
	}
	public static String getXHH() {
		return XHH;
	}
	public static void setXHH(String xhh) {
		DBSMS.XHH = xhh;
	}
	public static String getXHH1() {
		return XHH1;
	}
	public static void setXHH1(String xhh1) {
		DBSMS.XHH1 = xhh1;
	}
	public static String getdesc(String a){
    	if(a.equals("-1")){
    		return "输入参数不正确，请检查机构代码，业务类型，等输入参数是否为空";
    	}else if(a.equals("-2")){
    		return "机构不存在，请检查机构代码是否正确";
    	}else if(a.equals("-3")){
    		return "机构没有对应的短信服务类型";
    	}else if(a.equals("-4")){
    		return "客户端ip地址不正确（当需要ip校验时）";
    	}else if(a.equals("-5")){
    		return "smsId与数据库重复（下发短信时，如果smsId 由客户端传入，该参数不能重复）";
    	}else if(a.equals("-6")){
    		return "内容含有非法关键字，请检查下发内容";
    	}else if(a.equals("-7")){
    		return "对应的号码下发失败，下发号码为空或其他错误，导致该号码发送失败";
    	}else if(a.equals("-8")){
    		return "访问频率过快";
    	}else{
    		return "未知错误:"+a;
    	}
    }
	private String SendSMS(String phone,String content,String type){
		log.debug("phone:"+phone);
		log.debug("content:"+content);
		log.debug("type:"+type);
		String reslutValue="";
		try{
			long startt=System.currentTimeMillis();
			SmsNewOperatorService service=null;
			SmsNewOperator_PortType sendNewMessage=null;
			StringHolder sendResMsg=new StringHolder();
            StringHolder errMsg=new StringHolder();
			String StrPortAddress=IP;
			URL portAddress = new URL(StrPortAddress);
			// 得到客户端服务
			service=new SmsNewOperatorServiceLocator();
			// 得到客户端stub
			sendNewMessage=service.getSmsNewOperator(portAddress);
			// 测试服务方法
			MtNewMessage message=new MtNewMessage();
			message.setPhoneNumber(phone);
			message.setContent(content);
			log.info("XHH:"+XHH);
			sendNewMessage.sendSms(XHH,type,message,sendResMsg,errMsg);  //DB
//			sendNewMessage.sendSms("8816","DHJZX",message,sendResMsg,errMsg);   //BUW
			log.debug("sendSmsResMsg:" + sendResMsg.value);
			log.debug("sendSmsErrMsg:" + errMsg.value);
            long endt=System.currentTimeMillis();
            log.debug("-----发送短信结束：发送1条，共耗时 " + (endt - startt) + " 毫秒");
            reslutValue=errMsg.value;
            log.debug("reslutValue:"+reslutValue);
		}catch(Exception e){
			log.error("SendSMS_error:"+getERRO(e));
		}
		return reslutValue;
	}
	private String getERRO(Exception e){
		String str="";
		try{
            StringWriter sw = new StringWriter();  
            e.printStackTrace(new PrintWriter(sw, true));  
            str = sw.toString(); 	
		}catch(Exception e1){
			str=e.toString();
			log.error("getERRO:"+e1.toString());
		}
		return str;
	}
	public void run(){
		log.info("---------------------都帮短信接口----------------------------");
		while(flag){
			try{
				log.info("sss:"+times);
				Hz=Integer.parseInt(times);
			}catch(Exception e){
				log.info("错误:"+e);
				log.info("因为获取运行频率出错，改为默认频率1分钟运行");
			}
			log.info("扫描documentout表中未处理的记录："+sql);
			List list=null;
			try{
				list=ftpbean.chaxun(sql);
			}catch(Exception e){
				log.error("扫描documentout表_error:"+getERRO(e));
			}
			if(list!=null){
				for(int i=0;i<list.size();i++){
					Map map=(Map)list.get(i); 
					String type=Util.filterForObject(map.get("stringfield1"));
					String mobile=Util.filterForObject(map.get("DocumentTo"));
					String DocumentPath=Util.filterForObject(map.get("DocumentPath"));
					String TrialCountLimit=Util.filterForObject(map.get("TrialCountLimit"));
					String DocumentOut_GUID=Util.filterForObject(map.get("DocumentOut_GUID"));
					if(1==1){
						if(1==1){
							Date d=new Date();
							LastTryDateTime=formatter.format(d);
							FinishDateTime=formatter.format(d);
                            String reslutValue=SendSMS(mobile,DocumentPath,type);
							if(reslutValue!=null&&reslutValue!=""){
								log.info("返回结果:"+reslutValue);
								if("-1".equals(reslutValue) || "-2".equals(reslutValue) || "-3".equals(reslutValue)|| "-4".equals(reslutValue)||"-5".equals(reslutValue)||"-5".equals(reslutValue) || "-7".equals(reslutValue) || "-8".equals(reslutValue)){							
									update_sql=" update DocumentOut set FailCode="+reslutValue+",FailDescription='"+getdesc(reslutValue)+"',Status=5,TrialCount=TrialCount+1,LastTryDateTime=to_date('"+LastTryDateTime+"','yyyy-mm-dd hh24:mi:ss'),FinishDateTime=to_date('"+FinishDateTime+"','yyyy-mm-dd hh24:mi:ss'),ModifiedDate=sysdate where DocumentOut_GUID='"+DocumentOut_GUID+"'";
									
								}else{					
									update_sql=" update DocumentOut set Status=1,TrialCount=TrialCount+1,LastTryDateTime=to_date('"+LastTryDateTime+"','yyyy-mm-dd hh24:mi:ss'),FinishDateTime=to_date('"+FinishDateTime+"','yyyy-mm-dd hh24:mi:ss'),ModifiedDate=sysdate where DocumentOut_GUID='"+DocumentOut_GUID+"'";
									
								}
								log.info("update_sql:"+update_sql);
								try{
									int a=ftpbean.update(update_sql);
									log.info("是否更新DocumentOut成功:"+a);
								}catch(Exception e){
									log.info("更新DocumentOut出错:"+e);
								}
								
							}else{
								log.info("DocumentOut查询无结果");
							}

							
						}else{
							log.info("手机号"+mobile+"StringFrield2字段错误");
						}
						
					}else{
						log.info("手机号"+mobile+"StringFrield2字段错误");
					}
				}
				
			}else{
				log.info("没有需要发送的短信");
			}
                
			try{
				Thread.sleep(Hz*1000);
			}catch(Exception e){
				log.error("定时错误:"+getERRO(e));
			}
		}
	}

	

}





















